﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SocketServer.ServerBase;
using SocketServer;
using LogLib;
using IUploading;

namespace SocketServer.ClientCommands
{
    public class Login : ClientRequestPackCommand<TransferDataPackge>
    {
        public IUpload Uploader = null;

        public string OutParams = "";

        public ClientRequestPackSession Session;

        public TransferServer Server = null;

        public override void ExecuteCommand(ClientRequestPackSession session, TransferDataPackge pack)
        {
            try
            {
                Session = session;
                Server = session.AppServer as TransferServer;
                Server.OnNewSessionRequestReceived(session, pack);
                if (!Server.Uploaders.ContainsKey(pack.InterfaceName))
                {
                    Log.WriteAsync("不存在的接口:" + pack.InterfaceName);
                    return;
                }
                Uploader = Server.Uploaders[pack.InterfaceName];
                if (Uploader == null)
                {
                    Log.WriteAsync("接口对象为空:" + pack.InterfaceName);
                    return;
                }
                string outstring = "";
                Uploader.Login(pack.InParams, out outstring);
                if (Uploader.Inited)
                {
                    OnLoginOK(outstring);
                }
                else
                {
                    OnLoginFailed(Uploader.ErrorMessage, outstring);
                }
            }          
            catch (Exception ex)
            {
                Log.WriteException(ex.ToString());
                Server.OnCatchException(session, Uploader, TransferAction.Login, ex);
                return;
            }
        }

        protected void OnLoginOK(string outParams)
        {
            TransferResponsePackge pack = new TransferResponsePackge(Uploader.InterfaceName, TransferAction.Login);
            pack.Success = true;
            pack.Message = "";
            pack.Result = TransferResult.LoginOK;
            pack.SetParams(outParams);
            if (Session.Connected)
            {
                Session.Send(pack);
            }            
            Server.ReportTransferReponse(pack);
        }

        protected void OnLoginFailed(string reasonMsg, string outParams)
        {
            TransferResponsePackge pack = new TransferResponsePackge(Uploader.InterfaceName, TransferAction.Login);
            pack.Success = true;
            pack.Message = reasonMsg;
            pack.Result = TransferResult.LoginFailed;
            pack.SetParams(outParams);
            if (Session.Connected)
            {
                Session.Send(pack);
            }       
            Server.ReportTransferReponse(pack);
        }
    }
}
